﻿using Newtonsoft.Json;
using System;
using System.Net.Http;

namespace Common
{
    public class HttpUtil
    {

        // 泛型：Get请求
        public static T GetResponse<T>(string url, int timeoutSeconds = 5) where T : class, new()
        {
            var resultStr = GetResponse(url, timeoutSeconds);

            return JsonConvert.DeserializeObject<T>(resultStr);
        }

        // Get请求
        public static string GetResponse(string url, int TimeoutSeconds = 5)
        {
            string result = string.Empty;

            using (HttpClient httpClient = new HttpClient() { Timeout = new TimeSpan(0, 0, TimeoutSeconds) })
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = httpClient.GetAsync(url).Result;

                if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result;
                }
            }
            return result;
        }
    }
}
